<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2018 http://www.donglixia.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: 十万马 <962863675@qq.com>
// +----------------------------------------------------------------------
// | DateTime: 2018-02-09 16:17
// +----------------------------------------------------------------------

namespace app\admin_fussen\controller;

use app\admin_fussen\model\UserDept;
use think\Request;

class Dept extends Base
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->currentModel = new UserDept();//实例化当前模型
    }

    public function index()
    {
        $deptList = $this->currentModel->field('dept_id,pid,dept_name')->order('sort_num')->select();
        $deptList = \Tree::get_Table_tree($deptList, 'dept_name', 'dept_id');
        $this->assign('deptList', $deptList);
        return $this->fetch();
    }

    /**
     * 获取数据列表
     */
    public function getDataList()
    {
        $param = $this->request->param();
        $map = [];
        if (!empty($param['dept_name'])) {
            $map['dept_name'] = ['like', '%'.$param['dept_name'].'%'];
        }

        $count = $this->currentModel->where($map)->count();
        $list = $this->currentModel->where($map)
            ->page($param['page'], $param['limit'])
            ->order('sort_num')
            ->field('dept_id,pid,dept_name,dept_name as dept_name_text')
            ->select();
        $list = \Tree::get_Table_tree($list, 'dept_name_text', 'dept_id');
        return ['code'=>0, 'msg'=>'', 'count'=>$count, 'data'=>$list];
    }

    /**
     * 保存数据
     */
    public function save()
    {
        $param = $this->request->param();//获取请求数据
        //验证数据
        $result = $this->validate($param, 'UserDept');
        if ($result !== true) {
            $this->error($result);
        }

        try {
            //保存数据
            $this->currentModel->save($param);
        } catch (\Exception $e) {
            $msg = !empty($this->currentModel->getError()) ? $this->currentModel->getError() : $e->getMessage();
            save_error_log($msg.' ['.$e->getFile().':'.$e->getLine().']');
            $this->error($msg);
        }
        $this->success('保存成功！', 'index');
    }

    /**
     * 获取部门列表，树状Table_tree
     */
    public function getDeptList()
    {
        return $this->currentModel->getDeptTableTree();
    }
}

